package com.iwomy.secureplat.platform.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;

import com.iwomy.secureplat.admin.api.entity.SysDept;
import com.iwomy.secureplat.common.core.util.R;
import com.iwomy.secureplat.common.security.util.SecurityUtils;
import com.iwomy.secureplat.platform.dto.BasicAuthorizationRecordDTO;
import com.iwomy.secureplat.platform.dto.DeviceModelRequestDTO;
import com.iwomy.secureplat.platform.entity.*;
import com.iwomy.secureplat.platform.exception.PlatformException;
import com.iwomy.secureplat.platform.utils.DeptFillUtils;
import com.iwomy.secureplat.platform.utils.RemoteDeptUtils;
import com.iwomy.secureplat.platform.mapper.BasicAuthorizationRecordMapper;
import com.iwomy.secureplat.platform.service.BasicAuthorizationRecordService;
import com.iwomy.secureplat.platform.vo.BasicAuthorizationRecordVO;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.iwomy.secureplat.platform.vo.BasicDeviceModelVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 授权记录表
 *
 * @author pig
 * @date 2023-11-13 18:06:03
 */
@Service
public class BasicAuthorizationRecordServiceImpl extends ServiceImpl<BasicAuthorizationRecordMapper, BasicAuthorizationRecordEntity> implements BasicAuthorizationRecordService {

	@Autowired
	private RemoteDeptUtils remoteDeptUtils;

	@Override
	public Page<BasicAuthorizationRecordVO> getBasicAuthorizationRecordPage(Page page, BasicAuthorizationRecordDTO basicAuthorizationRecordDTO) {

		//多表查询
		MPJLambdaWrapper<BasicAuthorizationRecordEntity> wrapper = new MPJLambdaWrapper<>();
		wrapper.selectAll(BasicAuthorizationRecordEntity.class)

				.selectAs(BasicDeviceTypeEntity::getTypeName, BasicAuthorizationRecordVO::getDeviceType)
				.selectAs(BasicDeviceModelEntity::getDeviceModelName, BasicAuthorizationRecordVO::getDeviceModelName)

				.leftJoin(BasicDeviceTypeEntity.class, BasicDeviceTypeEntity::getId, BasicAuthorizationRecordEntity::getDeviceTypeId)
				.leftJoin(BasicDeviceModelEntity.class, BasicDeviceModelEntity::getId, BasicAuthorizationRecordEntity::getDeviceModelId)
				.in(BasicAuthorizationRecordEntity::getAuthorizedDeptId,SecurityUtils.getUser().getDeptId());


		if (ObjectUtil.isNotEmpty(basicAuthorizationRecordDTO.getDeviceModelId())) {
			wrapper.eq(BasicAuthorizationRecordEntity::getDeviceModelId, basicAuthorizationRecordDTO.getDeviceModelId());
		}
		if (ObjectUtil.isNotEmpty(basicAuthorizationRecordDTO.getDeptId())) {
			wrapper.in(BasicAuthorizationRecordEntity::getDeptId, basicAuthorizationRecordDTO.getDeptId());
		}

		Page<BasicAuthorizationRecordVO> basicAuthorizationRecordPage = this.getBaseMapper().selectJoinPage(page, BasicAuthorizationRecordVO.class, wrapper);

		DeptFillUtils.fill(basicAuthorizationRecordPage);
		return basicAuthorizationRecordPage;
	}

	@Override
	public R newlyAdded(DeviceModelRequestDTO deviceModelRequestDTO) {
		if (deviceModelRequestDTO.getDeptId().equals(SecurityUtils.getUser().getDeptId())){
			throw new PlatformException("不能给自己授权");
		}
		List<BasicDeviceModelVO> deviceModelList = deviceModelRequestDTO.getDeviceModelList();
		List<BasicAuthorizationRecordEntity> basicAuthorizationRecord = deviceModelList.stream()
				.map(deviceModel -> {
					BasicAuthorizationRecordEntity wrapperEntity = new BasicAuthorizationRecordEntity();
					wrapperEntity.setDeptId(deviceModelRequestDTO.getDeptId());
					wrapperEntity.setDeviceModelId(deviceModel.getId());
					wrapperEntity.setDeviceTypeId(deviceModel.getDeviceTypeId());
					LambdaQueryWrapper<BasicAuthorizationRecordEntity> wrapper = Wrappers.lambdaQuery(wrapperEntity);
					BasicAuthorizationRecordEntity one = this.getOne(wrapper);
					if (ObjectUtil.isNotNull(one)) {
						throw new PlatformException("请不要重复授权");
					}
					BasicAuthorizationRecordEntity authorizationRecord = new BasicAuthorizationRecordEntity();
					authorizationRecord.setDeptId(deviceModelRequestDTO.getDeptId());
					authorizationRecord.setAuthorizedDeptId(SecurityUtils.getUser().getDeptId());
					authorizationRecord.setDeviceTypeId(deviceModel.getDeviceTypeId());
					authorizationRecord.setDeviceModelId(deviceModel.getId());
					authorizationRecord.setDeviceTypeName(deviceModel.getDeviceType());
					authorizationRecord.setDeviceModelName(deviceModel.getDeviceModelName());
					authorizationRecord.setCommunicationModelId(deviceModel.getCommunicationModelId());
					authorizationRecord.setOperatorId(deviceModel.getOperatorId());
					authorizationRecord.setState(10);
					return authorizationRecord;
				}).collect(Collectors.toList());

		return R.ok(this.saveBatch(basicAuthorizationRecord));
	}

	@Override
	public R newlyRemoveBatchByIds(Long[] ids) {
		LambdaQueryWrapper<BasicAuthorizationRecordEntity> authorizationWrapper = new LambdaQueryWrapper<>();
		authorizationWrapper.in(BasicAuthorizationRecordEntity::getId,ids);
		List<BasicAuthorizationRecordEntity> authorizationRecords = this.getBaseMapper().selectList(authorizationWrapper);

		List<Long> allLowerAuthIds = new ArrayList<>();
		List<Long> lowerDeptIds = new ArrayList<>();
		for (BasicAuthorizationRecordEntity authorizationRecord: authorizationRecords) {
			List<SysDept> deptList = (List<SysDept>) remoteDeptUtils.getDescendantList(authorizationRecord.getDeptId()).getData();
			if (deptList!=null){
				lowerDeptIds = deptList.stream().map(SysDept::getDeptId).collect(Collectors.toList());
			}
			LambdaQueryWrapper<BasicAuthorizationRecordEntity> wrapper = new LambdaQueryWrapper<>();
			wrapper.in(BasicAuthorizationRecordEntity::getAuthorizedDeptId,lowerDeptIds)
					.eq(BasicAuthorizationRecordEntity::getDeviceTypeId,authorizationRecord.getDeviceTypeId())
					.eq(BasicAuthorizationRecordEntity::getDeviceModelId,authorizationRecord.getDeviceModelId());
			List<Object> deptIds = this.getBaseMapper().selectObjs(wrapper);

			List<Long> authIdList = deptIds.stream().map(obj -> Long.valueOf(obj.toString())).collect(Collectors.toList());
			allLowerAuthIds.addAll(authIdList);
		}

		Long[] idsArray = allLowerAuthIds.toArray(new Long[0]); // 将 allLowerAuthIds 转换为 Long[]

		idsArray = Arrays.copyOf(idsArray, idsArray.length + ids.length); // 扩展数组长度放ids
		System.arraycopy(ids, 0, idsArray, allLowerAuthIds.size(), ids.length); // 复制 ids 到 idsArray

		return R.ok(this.removeBatchByIds(CollUtil.toList(idsArray)));
	}

}